<?php

namespace app\api\controller;

use app\common\model\ConvertGoods;
use app\common\model\FosterGoods;
use app\common\model\FosterGoodsCategory;
use app\common\model\Goods;
use app\common\model\GoodsCategory;
use app\common\model\JifenGoods;
use app\common\model\MonitorClass;
use app\common\model\Monitors;
use app\common\model\StockGoods;
use app\common\util\HttpClient;
use app\common\util\MyException;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;

/**
 * @Apidoc\Title("商品相关")
 */
class GoodsApi extends Base
{
    /**
     * @Apidoc\Title("商品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_goods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="",desc="用户id")
     * @Apidoc\Param("cate_id", type="int",default="",desc="分类id")
     * @Apidoc\Param("is_recommend", type="int",default="",desc="是否推荐1是")
     * @Apidoc\Param("is_seckill", type="int",default="",desc="是否秒杀1是")
     */
    public function get_goods_list(){
        $pi = input('pageIndex',1);
        $ps = input('pageSize',20);
        $is_recommend = input('is_recommend');
        $is_seckill = input('is_seckill');
        $cate_id = input('cate_id');
        $where="is_on_sale=1";
        if ($is_recommend){
            $where.=" and is_recommend=1";
        }
        if ($cate_id){
            $cate=GoodsCategory::find($cate_id);
            if ($cate){
                if ($cate['level']==1){
                    $where.=" and cat_id_1={$cate_id}";
                }else{
                    $where.=" and cat_id_2={$cate_id}";
                }
            }
        }
        if ($is_seckill){
            $time=time();
            $where.=" and {$time}>=seckill_start_time and {$time}<seckill_end_time";
        }
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,goods_name,sales_sum,seckill_start_time,seckill_end_time,seckill_price,store_count";
        $list = Goods::where($where)
            ->order('sort asc,goods_id desc')
            ->page($pi, $ps)
            ->field($field)
            ->select()->each(function ($item){
                $item['goods_price']=$item['price'];
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("商品详情数据")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/goods_xq")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     * @Apidoc\Returned("goods_images", type="string",default="",desc="商品主图")
     * @Apidoc\Returned("goods", type="array",default="{}",desc="商品数据")
     * @Apidoc\Returned("edit", type="int",default="0",desc="该用户是否收藏")
     * @Apidoc\Returned("filter_spec", type="array",default="{}",desc="商品规格图片，属性")
     * @Apidoc\Returned("spec_goods_price", type="array",default="{}",desc="商品规格")
     */
    public function goods_detail()
    {
        //获取商品id并强制转换为整型数据
        $goods_id = input("id/d");
        $goodsModel = new Goods();
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,ship_price,goods_name,sales_sum,seckill_start_time,seckill_end_time,seckill_price,store_count,goods_remark,store_id,goods_content";
        $where="goods_id={$goods_id} and is_on_sale=1";
        $goods = $goodsModel::where($where)->field($field)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        $user_id = 0;
        $edit = 0;
        if ($this->user_id) {
            $user_id = $this->user_id;
        }
        if ($user_id) {
            $coll = Db::name('goods_collect')->where('user_id=' . $user_id . ' and goods_id=' . $goods_id)->find();
            if ($coll) {
                $edit = 1;//已收藏
            }
            //保存浏览记录
            $goods->add_visit_log($user_id,$goods);
        }
        $goods_imgs[]=['image_url'=>$goods['goods_img']];
        foreach ($goods->goods_images as $image) {
            $image['image_url'] = SITE_URL . $image['image_url'];
            unset($image['img_id']);
            unset($image['goods_id']);
            $goods_imgs[]=$image;
        }
        $spec_goods_price  = Db::name('spec_goods_price')
            ->where("goods_id",$goods_id)
            ->field("key,price,store_count,level_price,item_id")
            ->select()->each(function ($item){
                return $item;
            });
        $map = $this->get_spec($goods_id,$goods);
        $item_id=0;
        $item_store_count=$goods['store_count'];
        //商品价格 如果有规格 则按照规格
        if ($map['spec_key']){
            $spec_goods_prices  = Db::name('spec_goods_price')
                ->where("goods_id",$goods_id)
                ->column('price,item_id,store_count,level_price','key');
            $item_id=$spec_goods_prices[$map['spec_key']]['item_id'];
            $item_store_count=$spec_goods_prices[$map['spec_key']]['store_count'];
        }
        $goods['goods_price']=$goods['price'];
        $goods['goods_content']=str_replace("<img src=\"","<img style='width:100%;' src=\"".SITE_URL,$goods['goods_content']);
        $goods['store_name']=$goods['store']['store_name'];
        $goods['store_logo']=$goods['store']['store_logo'];
        $goods['store_address']=$goods['store']['province'].$goods['store']['city'].$goods['store']['district'];
        $goods['store_contacts_mobile']=$goods['store']['contacts_mobile'];
        unset($goods['store']);
        //商品数据
        $data['goods'] = $goods;
        //该用户是否收藏
        $data['edit'] = $edit;
        $data['goods_imgs'] = $goods_imgs;
        $data['item_str'] = $map['str'];
        $data['item_id'] = $item_id;
        $data['item_store_count'] = $item_store_count;
        $data['item_img'] = $map['item_img'];
        $data['filter_spec'] = $map['filter'];
        $data['spec_goods_price'] = $spec_goods_price;
        throw new MyException('获取成功',200,$data);
    }
    //获取商品规格
    private function get_spec($goods_id,$goods=array()){
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys=Db::name('spec_goods_price')->where('goods_id',$goods_id)->order('store_count desc')->column('key');
        $spec_key=[];
        $str='';
        $item_img=SITE_URL.Db::name('goods')->where('goods_id',$goods_id)->value('goods_img');
        $filter_spec = [];
        if($keys) {
            $key=implode('_',$keys);
            $keys = str_replace('_',',',$key);
            $k8=explode(',',$keys);
            $filter_spec=Db::name('spec')
                ->alias('a')
                ->join('spec_item b','a.id=b.spec_id','inner')
                ->whereIn('b.id',$keys)
                ->group('b.spec_id')
                ->field('b.spec_id,a.name')
                ->order('a.sort')
                ->select()->toArray();
            foreach ($filter_spec as $k1 => $v1){
                $child=Db::name('spec_item')->where('spec_id',$v1['spec_id'])->whereIn('id',$k8)->select()->toArray();
                foreach ($child as $k2 => $v2){
                    $spec_image=Db::name('spec_image')->where("spec_image_id={$v2['id']} and goods_id=$goods_id")->value('src');
                    $child[$k2]['image']=$spec_image ? SITE_URL.$spec_image : null;
                }
                $filter_spec[$k1]['child']=$child;
                $filter_spec[$k1]['selected']=$child[0]['id'];
                $str.=$child[0]['item'].' ';
                $spec_key[]=$child[0]['id'];
            }
            if ($filter_spec[0]['child'][0]['image']){
                $item_img=$filter_spec[0]['child'][0]['image'];
            }
        }
        if ($spec_key){
            sort($spec_key);
        }
        $piece=$goods['piece'] ?: "件";
        $str.= "1" . $piece;
        $map['filter']=$filter_spec;
        $map['str']=$str;
        $map['item_img']=$item_img;
        $map['spec_key']=implode('_',$spec_key);
        return $map;
    }
    /**
     * @Apidoc\Title("商品分享")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/goods_fx")
     * @Apidoc\Param("id",type="int",require=true,default="",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="",desc="用户id")
     * @Apidoc\Param("type",type="int",default="",desc="类型1商城商品2认养商品")
     * @Apidoc\Returned("share_img", type="string",default="",desc="分享图")
     */
    public function goods_share(){
        $type=input('type');
        if (!in_array($type,[1,2])){
            throw new MyException('提交参数有误');
        }
        $goods_id = input("id/d");
        if ($type==1){
            $goodsModel = new Goods();
        }else{
            $goodsModel = new FosterGoods();
        }
        $where="goods_id={$goods_id} and is_on_sale=1";
        $goods = $goodsModel::where($where)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        require_once root_path('vendor')."phpqrcode/phpqrcode.php";
        //生成二维码
        $url=SITE_URL.'/#/pages/auth/register?rekey='.$this->user_id;
        \QRcode::png($url,'assets/share/'.$goods['goods_id'].'.png','L',7,2);
//        header('Content-Type: image/png');
        //商品图和背景图合并生成推广1
        $base_name = 'assets/share/share.png';
        $good_img = '.'.str_replace($this->site_url,'',$goods['goods_img']);
        $base_name = imagecreatefrompng($base_name);
        $img_type=pathinfo($good_img, PATHINFO_EXTENSION);
        if ($img_type){
            if (in_array(strtolower($img_type),['jpg','jpeg'])){
                $img_type="jpeg";
            }
            $func="imagecreatefrom{$img_type}";
            $good_img_path=$func($good_img);
        }else{
            throw new MyException('商品不存在');
        }
        $width=imagesx($good_img_path);
        $height=imagesy($good_img_path);
        imagecopyresampled($base_name, $good_img_path, 0, 0, 0, 0, 750, 700, $width, $height);
//        imagecopymerge($base_name, $good_img_path, 0, 0, 0, 0, 750, 750, 100);
        imagejpeg($base_name,'assets/share/'.'tg1_'.$goods['goods_id'].'.jpg');

        //推广1和二维码合并生成推广2
        $tg1 = imagecreatefromjpeg('assets/share/'.'tg1_'.$goods['goods_id'].'.jpg');
        $ewm = imagecreatefrompng('assets/share/'.$goods['goods_id'].'.png');
        imagecopyresampled($tg1, $ewm, 450, 1020, 0, 0, imagesx($ewm), imagesy($ewm), imagesx($ewm), imagesy($ewm));
//        imagecopymerge($tg1, $ewm, 460, 1020, 0, 0, 330, 330, 100);
        imagejpeg($tg1,'assets/share/'.'tg2_'.$goods['goods_id'].'.jpg');
        //标题换行
        mb_internal_encoding("UTF-8");// 设置编码
        //这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        $text3=$goods['goods_name'];
        $fontSize=20;
        $width=730;
        $font='resource/font/msyh.ttf';

        //将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($text3);$i++) {
            $letter[] = mb_substr($text3, $i, 1);
        }
        foreach ($letter as $l) {
            $teststr = $content." ".$l;
            $fontBox = imagettfbbox($fontSize, 0, $font, $teststr);
            //判断拼接后的字符串是否超过预设的宽度
            if (($fontBox[2] > $width) && ($content !== "")) {
                $content .= "\n";
            }
            $content .= $l;
        }
        //写入标题
        $tg2 = imagecreatefromjpeg('assets/share/'.'tg2_'.$goods['goods_id'].'.jpg');
//        $color2 = imagecolorallocate($tg2, 78,84,93);
        $color2 = imagecolorallocate($tg2, 26, 24, 27);
        imagettftext($tg2, 20, 0, ceil(($width - $fontBox[2]) / 2), 760, $color2, $font, $content );
        imagejpeg($tg2,'assets/share/'.'tg3_'.$goods['goods_id'].'.jpg');

        //写入本店价
        $tg3 = imagecreatefromjpeg('assets/share/'.'tg3_'.$goods['goods_id'].'.jpg');
        $color3 = imagecolorallocate($tg3, 255,255,255);
        imagettftext($tg3, 22, 0, 30, 850, $color3, $font, '本店价：'.$goods['goods_price']);
        imagejpeg($tg3,'assets/share/'.'tg4_'.$goods['goods_id'].'.jpg');

        if ($type==1){
            //写入市场价
            $tg5 = imagecreatefromjpeg('assets/share/'.'tg4_'.$goods['goods_id'].'.jpg');
            $color5 = imagecolorallocate($tg5, 26, 24, 27);
            imagettftext($tg5, 22, 0, 400, 850, $color5, $font, '市场价：'.$goods['market_price']);
            imagejpeg($tg5,'assets/share/'.'tg5_'.$goods['goods_id'].'.jpg');
        }else{
            //写入限购
            $tg5 = imagecreatefromjpeg('assets/share/'.'tg4_'.$goods['goods_id'].'.jpg');
            $color5 = imagecolorallocate($tg5, 26, 24, 27);
            imagettftext($tg5, 22, 0, 400, 850, $color5, $font, '限购：'.$goods['buy_max']);
            imagejpeg($tg5,'assets/share/'.'tg5_'.$goods['goods_id'].'.jpg');
        }

        //写入销量
        $tg6 = imagecreatefromjpeg('assets/share/'.'tg5_'.$goods['goods_id'].'.jpg');
        $color6 = imagecolorallocate($tg6, 26, 24, 27);
        imagettftext($tg6, 22, 0, 30, 920, $color6, $font, '销量：'.$goods['sales_sum']);
        imagejpeg($tg6,'assets/share/'.'tg6_'.$goods['goods_id'].'.jpg');

        //写入库存
        $tg7 = imagecreatefromjpeg('assets/share/'.'tg6_'.$goods['goods_id'].'.jpg');
        $color7 = imagecolorallocate($tg7, 26, 24, 27);
        imagettftext($tg7, 22, 0, 400, 920, $color7, $font, '库存：'.$goods['store_count']);
        imagejpeg($tg7,'assets/share/'.'tg_'.$goods['goods_id'].'.jpg');
        //删除图片
        @unlink ('assets/share/'.$goods['goods_id'].'.png');
        @unlink ('assets/share/'.'tg1_'.$goods['goods_id'].'.jpg');
        @unlink ('assets/share/'.'tg2_'.$goods['goods_id'].'.jpg');
        @unlink ('assets/share/'.'tg3_'.$goods['goods_id'].'.jpg');
        @unlink ('assets/share/'.'tg4_'.$goods['goods_id'].'.jpg');
        @unlink ('assets/share/'.'tg5_'.$goods['goods_id'].'.jpg');
        @unlink ('assets/share/'.'tg6_'.$goods['goods_id'].'.jpg');
        $share_path=SITE_URL.'/assets/share/'.'tg_'.$goods['goods_id'].'.jpg';
        throw new MyException('获取成功',200,['share_path'=>$share_path]);
    }
    /**
     * @Apidoc\Title("认养分类列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_ry_cates")
     */
    public function get_foster_goods_category(){
        $where="is_show=1";
        $filed = "id,name";
        $list = FosterGoodsCategory::where($where)
            ->order('sort asc,id desc')
            ->field($filed)
            ->select()->each(function ($item){
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("认养商品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_ry_goods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="",desc="用户id")
     * @Apidoc\Param("cate_id", type="int",default="",desc="分类id")
     * @Apidoc\Param("is_recommend", type="int",default="",desc="是否推荐1是")
     */
    public function get_foster_goods(){
        $pi = input('pageIndex',1);
        $ps = input('pageSize',20);
        $is_recommend = input('is_recommend');
        $cate_id = input('cate_id');
        $where="is_on_sale=1";
        if ($is_recommend){
            $where.=" and is_recommend=1";
        }
        if ($cate_id){
            $where.=" and cat_id_1={$cate_id}";
        }
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,day_sy,sy_day,yield,goods_name,sales_sum,unit,store_count,store_id";
        $list = FosterGoods::where($where)
            ->with(['store'])
            ->order('sort asc,goods_id desc')
            ->page($pi, $ps)
            ->field($field)
            ->select()->each(function ($item){
                $item['take_num']=$item['take_num_text'];
                $item['take_bili']=$item['take_bili_text'];
                $item['head_urls']=$item['take_user_head'];
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("认养商品详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/ry_goods_xq")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     */
    public function foster_goods_detail()
    {
        $goods_id = input("id/d");
        $goodsModel = new FosterGoods();
        $where="is_on_sale=1 and goods_id={$goods_id}";
        $field = "goods_id,goods_img,goods_imgs,goods_price,day_sy,sy_day,yield,goods_name,sales_sum,store_count,goods_content,goods_remark,store_id";
        $goods = $goodsModel->where($where)->field($field)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        $goods['goods_img'] = SITE_URL . $goods['goods_img'];
        $goods_imgs[]=$goods['goods_img'];
        if ($goods['goods_imgs']){
            foreach ($goods['goods_imgs'] as $image) {
                $temp_img = SITE_URL . $image;
                $goods_imgs[]=$temp_img;
            }
        }
        $goods['goods_content']=str_replace("<img src=\"","<img style='width:100%;' src=\"".SITE_URL,$goods['goods_content']);
        $goods['store_name']=$goods['store']['store_name'];
        $goods['store_logo']=$goods['store']['store_logo'];
        $goods['store_address']=$goods['store']['province'].$goods['store']['city'].$goods['store']['district'];
        $goods['store_contacts_mobile']=$goods['store']['contacts_mobile'];
        unset($goods['store']);
        //赠送储备金比例
        $cbj_bl=getSysConfig('rate.cbj_bl');
        $given_cbj=$goods['goods_price']*$cbj_bl;
        //商品数据
        $data['goods'] = $goods;
        $data['goods_imgs'] = $goods_imgs;
        $data['given_cbj'] = $given_cbj;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("兑换商品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_dh_goods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="",desc="用户id")
     * @Apidoc\Param("wid", type="int",default="",desc="wallet表id")
     */
    public function get_convert_goods(){
        $pi = input('pageIndex',1);
        $ps = input('pageSize',20);
        $wid = input('wid');
        $where="is_on_sale=1";
        if ($wid){
            $where.=" and wid={$wid}";
        }
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,market_price,goods_price,goods_name,sales_sum,store_count";
        $list = ConvertGoods::where($where)
            ->order('sort asc,goods_id desc')
            ->page($pi, $ps)
            ->field($field)
            ->select()->each(function ($item){
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("兑换商品详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/dh_goods_xq")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     */
    public function convert_goods_detail()
    {
        $goods_id = input("id/d");
        $goodsModel = new ConvertGoods();
        $where="is_on_sale=1 and goods_id={$goods_id}";
        $field = "goods_id,goods_name,goods_img,goods_imgs,goods_price,goods_remark,goods_content,wid,sales_sum,store_count";
        $goods = $goodsModel->where($where)->field($field)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        $goods['goods_img'] = SITE_URL . $goods['goods_img'];
        $goods_imgs[]=$goods['goods_img'];
        if ($goods['goods_imgs']){
            foreach ($goods['goods_imgs'] as $image) {
                $temp_img = SITE_URL . $image;
                $goods_imgs[]=$temp_img;
            }
        }
        $goods['goods_content']=str_replace("<img src=\"","<img style='width:100%;' src=\"".SITE_URL,$goods['goods_content']);
        $goods['name']=$goods['qianbao']['name'];
        unset($goods['qianbao']);
        //商品数据
        $data['goods'] = $goods;
        $data['goods_imgs'] = $goods_imgs;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("积分商品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_jf_goods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="",desc="用户id")
     * @Apidoc\Param("cate_id", type="int",default="",desc="分类id")
     * @Apidoc\Param("is_recommend", type="int",default="",desc="是否推荐1是")
     */
    public function get_jifen_goods_list(){
        $pi = input('pageIndex',1);
        $ps = input('pageSize',20);
        $where="is_on_sale=1";
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,goods_name,sales_sum,store_count";
        $list = JifenGoods::where($where)
            ->order('sort asc,goods_id desc')
            ->page($pi, $ps)
            ->field($field)
            ->select()->each(function ($item){
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("积分商品详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/jf_goods_xq")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     */
    public function jifen_goods_detail()
    {
        $goods_id = input("id/d");
        $goodsModel = new JifenGoods();
        $where="is_on_sale=1 and goods_id={$goods_id}";
        $field = "goods_id,goods_name,goods_img,goods_imgs,goods_price,goods_remark,goods_content,sales_sum,store_count";
        $goods = $goodsModel->where($where)->field($field)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        $goods['goods_img'] = SITE_URL . $goods['goods_img'];
        $goods_imgs[]=$goods['goods_img'];
        if ($goods['goods_imgs']){
            foreach ($goods['goods_imgs'] as $image) {
                $temp_img = SITE_URL . $image;
                $goods_imgs[]=$temp_img;
            }
        }
        $goods['goods_content']=str_replace("<img src=\"","<img style='width:100%;' src=\"".SITE_URL,$goods['goods_content']);
        //商品数据
        $data['goods'] = $goods;
        $data['goods_imgs'] = $goods_imgs;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("进货商品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_jh_goods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="",desc="用户id")
     * @Apidoc\Param("wid", type="int",default="",desc="wallet表id")
     */
    public function get_stock_goods(){
        $pi = input('pageIndex',1);
        $ps = input('pageSize',20);
        $wid = input('wid');
        $where="is_on_sale=1";
        if ($wid){
            $where.=" and wid={$wid}";
        }
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,market_price,goods_price,goods_name,sales_sum,store_count";
        $list = StockGoods::where($where)
            ->order('sort asc,goods_id desc')
            ->page($pi, $ps)
            ->field($field)
            ->select()->each(function ($item){
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("进货商品详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/jh_goods_xq")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     */
    public function stock_goods_detail()
    {
        $goods_id = input("id/d");
        $goodsModel = new StockGoods();
        $where="is_on_sale=1 and goods_id={$goods_id}";
        $field = "goods_id,goods_name,goods_img,goods_imgs,goods_price,goods_remark,goods_content,wid,sales_sum,store_count";
        $goods = $goodsModel->where($where)->field($field)->find();
        if (empty($goods)) {
            throw new MyException('商品不存在或已下架');
        }
        $goods['goods_img'] = SITE_URL . $goods['goods_img'];
        $goods_imgs[]=$goods['goods_img'];
        if ($goods['goods_imgs']){
            foreach ($goods['goods_imgs'] as $image) {
                $temp_img = SITE_URL . $image;
                $goods_imgs[]=$temp_img;
            }
        }
        $goods['goods_content']=str_replace("<img src=\"","<img style='width:100%;' src=\"".SITE_URL,$goods['goods_content']);
        $goods['name']=$goods['qianbao']['name'];
        unset($goods['qianbao']);
        //商品数据
        $data['goods'] = $goods;
        $data['goods_imgs'] = $goods_imgs;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("监控分类")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_monitor_class")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Returned("data", type="array",default="{}",desc="list:监控分类列表")
     */
    public function monitor_class()
    {
        $where[]=['is_open','=',1];
        $data['list']=MonitorClass::where($where)->order('sort asc,id desc')->select();
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("监控列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_monitor_list")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param("c_id",type="int",default=0,desc="监控分类ID,0为全部")
     * @Apidoc\Returned("data", type="array",default="{}",desc="list:监控列表数据")
     */
    public function monitor_list()
    {
        $c_id=input('c_id',0);
        $where[]=['is_open','=',1];
        if($c_id){
            $where[]=['c_id','=',$c_id];
        }
        $list=Monitors::where($where)->order('sort asc,id desc')->select()->each(function ($item){
            $item['img']=SITE_URL.$item['img'];
            return $item;
        });
        $data['list']=$list;
        throw new MyException('获取成功',200,$data);
    }
    /**
     * @Apidoc\Title("监控详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_monitor_detail")
     * @Apidoc\Param("serial",type="string",default=NULL,desc="监控设备号")
     * @Apidoc\Returned("data", type="array",default="{}",desc="url:监控页面")
     */
    public function monitor_detail()
    {
        $serial=input('serial');
        $info=Monitors::where('serial',$serial)->find();
        $Http = new HttpClient();
        $result=$Http->getToken();
        $token=$result['data']['accessToken'];
        $data['url']='https://open.ys7.com/ezopen/h5/live?autoplay=1&audio=1&accessToken='.$token.'&hd=1&deviceSerial='.$serial.'&validCode='.$info['code'].'&channelNo=1';
        throw new MyException('获取成功',200,$data);
    }
}
